package com.example.nonggo.viewpager;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import androidx.viewpager.widget.ViewPager;

public class VerticalViewPager extends ViewPager {

    public VerticalViewPager(Context context) {
        super(context);
        init();
    }

    public VerticalViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // 设置页面切换动画为垂直方向
        setPageTransformer(true, new VerticalPageTransformer());
        // 关闭默认的滑动动画
        setOverScrollMode(View.OVER_SCROLL_NEVER);
    }

    // 交换触摸事件的 X 和 Y 坐标
    private MotionEvent swapTouchEvent(MotionEvent event) {
        float width = getWidth();
        float height = getHeight();
        float swappedX = (event.getY() / height) * width;
        float swappedY = (event.getX() / width) * height;
        event.setLocation(swappedX, swappedY);
        return event;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        boolean intercepted = super.onInterceptTouchEvent(swapTouchEvent(event));
        swapTouchEvent(event); // 恢复坐标，确保后续事件正确
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(swapTouchEvent(event));
    }

    // 垂直页面切换动画
    private static class VerticalPageTransformer implements PageTransformer {
        @Override
        public void transformPage(View page, float position) {
            if (position <= -1 || position >= 1) {
                // 完全不可见的页面
                page.setTranslationY(0);
            } else if (position < 0) {
                // 向左滑出（向上滚动）
                page.setTranslationY(-page.getHeight() * Math.abs(position));
            } else {
                // 向右滑入（向下滚动）
                page.setTranslationY(page.getHeight() * position);
            }
        }
    }
}
